package utils;

import entity.Share;
import sun.security.provider.SHA;

import javax.persistence.criteria.CriteriaBuilder;
import java.io.IOException;
import java.util.*;

/**
 * Created by 梅晨 on 2017/8/14.
 */
public class Share2SQL {
    static HashMap<String,Integer> score = new HashMap<String, Integer>();
    public static void run()throws IOException{
        String today = new java.sql.Date(new java.util.Date().getTime()).toString();
        String filePath = "C:\\Users\\梅晨\\PycharmProjects\\weiboSpider\\stores\\" + today + ".txt";
        List<Share> shares = getShares(filePath);
        score = categoryScore(shares);
        SqlUtil sqlUtil = new SqlUtil();
        sqlUtil.insertShare(shares);
    }

    public static List<Share> getShares(String filepath)throws IOException{
        List<String> lines = IOUtils.getFileLines(filepath);
        List<Share> shares = new ArrayList<Share>();
        for(String line : lines){
            String[] strs = line.split(",");
            String category = strs[0];
            String code = strs[1];
            String name = strs[2];
            float riseandfall = 0;
            String num = strs[3].replace("%","");
            if(!num.equals("-")){
                riseandfall = Float.valueOf(num);
            }
            Share share = new Share();
            share.setCategory(category);
            share.setCode(code);
            share.setName(name);
            share.setRiseandfall(riseandfall);
            share.setDate(new java.sql.Date(new java.util.Date().getTime()));
            shares.add(share);
        }
        return shares;
    }

    public static HashMap<String,Integer> categoryScore(List<Share> shares){
        HashMap<String,Integer> map = new HashMap<String, Integer>();
        HashMap<String,Integer> result = new HashMap<String, Integer>();
        for(Share share : shares){
            if(share.getRiseandfall() > 0){
                if(!result.containsKey(share.getCategory())){
                    result.put(share.getCategory(),1);
                }else {
                    result.put(share.getCategory(),result.get(share.getCategory()) + 1);
                }
            }else if(share.getRiseandfall() < 0){
                if(!map.containsKey(share.getCategory())){
                    map.put(share.getCategory(), 1);
                }else {
                    map.put(share.getCategory(),map.get(share.getCategory()) + 1);
                }
            }
        }
        for(String category : result.keySet()) {
            int num = result.get(category);
            int num2 = 0;
            if(map.containsKey(category)) num2 = map.get(category);
            int val = (num + 1) * 100 / (num + num2 + 1);
            result.put(category, val);
        }
        return result;
    }
}
